//
//  SearchView.m
//  Dispatch
//
//  Created by hyeyeon on 14. 1. 14..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "SearchView.h"
#import "NKLabel.h"

#define starTotalCount(count)   [NSString stringWithFormat:@"%d %@",count,NSLocalizedString(@"starsearchresult", @"")]
#define issueTotalCount(count)  [NSString stringWithFormat:@"%d %@",count,NSLocalizedString(@"issuesearchresult", @"")]

@implementation SearchView
@synthesize responseData, currentKeyword;
@synthesize issueArray, issueCount, issueIsEnd, currentIssuePageNumber, issueImageURL;
@synthesize starArray, starCount, starIsEnd, currentStarPageNumber, starImageURL, searchFrame;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.searchFrame = frame;
        
        appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
        self.responseData = [NSMutableData data];
        self.backgroundColor = ColorFromRGB(0x413c43);
        
        issueArray = [[NSMutableArray alloc] init];
        starArray = [[NSMutableArray alloc] init];
        autoArray = [[NSMutableArray alloc] init];
        
        self.currentKeyword = @"";
        [self makeObject];
        [self makeIssueView];
        [self makeStarView];
        
        topMoveButton = [[UIButton alloc] initWithFrame:CGRectMake(mySize.width-10-35, frame.size.height-44-35-10, 35, 35)];
        [topMoveButton setImage:[UIImage imageNamed:@"btn_top"] forState:UIControlStateNormal];
        [topMoveButton addTarget:self action:@selector(topMoveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:topMoveButton];
        
        [self makeSearchBGView];
        
        [self starButtonAction:starButton];
        [self makeActivityIndicatorView];
        
    }
    return self;
}

#pragma mark - 생성

-(void)makeObject{
    
    //title
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mySize.width, 44+32)];
    titleView.backgroundColor = ColorFromRGB(0xe9e9e9);
    [self addSubview:titleView];
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 37, 44)];
    [backButton setImage:[UIImage imageNamed:@"btn_back02"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:backButton];
    
    mSearchView = [[UISearchBar alloc] initWithFrame:CGRectMake(backButton.frame.origin.x+backButton.frame.size.width+10, 4, mySize.width-backButton.frame.origin.x-backButton.frame.size.width-20, 44-10)];
    mSearchView.delegate = self;
    mSearchView.placeholder = @"search star";
    mSearchView.tintColor = ColorFromRGB(0xe9e9e9);
    if (deviceIOS7) {
        
        mSearchView.barTintColor = [UIColor clearColor];
    }
    mSearchView.backgroundColor = [UIColor whiteColor];
    [self addSubview:mSearchView];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(10, 44, mySize.width-20, 1)];
    line.backgroundColor = ColorFromRGB(0x2a2829);
    [self addSubview:line];
    
    UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(10, line.frame.origin.y, 17, 32)];
    icon.image = [UIImage imageNamed:@"icon_search_result"];
    [self addSubview:icon];
    
    resultCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(icon.frame.origin.x+icon.frame.size.width+5, icon.frame.origin.y, mySize.width-icon.frame.origin.x-icon.frame.size.width-10, 32)];
    resultCountLabel.backgroundColor = [UIColor clearColor];
    resultCountLabel.textColor = ColorFromRGB(0x2a2829);
    resultCountLabel.font = [UIFont systemFontOfSize:13];
    resultCountLabel.text = starTotalCount(0);
    [self addSubview:resultCountLabel];
    
    
    //스타&이슈버튼
    starButton = [[UIButton alloc] initWithFrame:CGRectMake(10, titleView.frame.origin.y+titleView.frame.size.height+10, 150, 29)];
    [starButton setBackgroundImage:[UIImage imageNamed:@"menu_star"] forState:UIControlStateNormal];
    [starButton setBackgroundImage:[UIImage imageNamed:@"menu_star_on"] forState:UIControlStateSelected];
    [starButton addTarget:self action:@selector(starButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [starButton setTitle:NSLocalizedString(@"Star", @"") forState:UIControlStateNormal];
    [starButton setTitleColor:ColorFromRGB(0x49a1d9) forState:UIControlStateNormal];
    [starButton setTitleColor:ColorFromRGB(0xffffff) forState:UIControlStateSelected];
    [self addSubview:starButton];
    
    issueButton = [[UIButton alloc] initWithFrame:CGRectMake(starButton.frame.origin.x+starButton.frame.size.width, starButton.frame.origin.y, 150, 29)];
    [issueButton setBackgroundImage:[UIImage imageNamed:@"menu_issue"] forState:UIControlStateNormal];
    [issueButton setBackgroundImage:[UIImage imageNamed:@"menu_issue_on"] forState:UIControlStateSelected];
    [issueButton addTarget:self action:@selector(issueButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [issueButton setTitle:NSLocalizedString(@"Issue", @"") forState:UIControlStateNormal];
    [issueButton setTitleColor:ColorFromRGB(0x49a1d9) forState:UIControlStateNormal];
    [issueButton setTitleColor:ColorFromRGB(0xffffff) forState:UIControlStateSelected];
    [self addSubview:issueButton];
    
}



//테이블생성
-(void)makeIssueView{
    issueTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, starButton.frame.origin.y+starButton.frame.size.height+10, mySize.width, searchFrame.size.height-starButton.frame.origin.y-starButton.frame.size.height-10)];
    issueTableView.tag = 1;
    issueTableView.delegate = self;
    issueTableView.dataSource = self;
    issueTableView.backgroundColor = [UIColor clearColor];
    issueTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addSubview:issueTableView];
    
    i_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - issueTableView.bounds.size.height, issueTableView.frame.size.width, issueTableView.bounds.size.height)];
    i_refreshHeaderView.delegate = self;
    [issueTableView addSubview:i_refreshHeaderView];
    [i_refreshHeaderView refreshLastUpdatedDate];
    
}
-(void)makeStarView{
    starTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, starButton.frame.origin.y+starButton.frame.size.height+10, mySize.width, searchFrame.size.height-starButton.frame.origin.y-starButton.frame.size.height-10)];
    starTableView.tag = 2;
    starTableView.delegate = self;
    starTableView.dataSource = self;
    starTableView.backgroundColor = [UIColor clearColor];
    starTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addSubview:starTableView];
    
    s_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - issueTableView.bounds.size.height, issueTableView.frame.size.width, issueTableView.bounds.size.height)];
    s_refreshHeaderView.delegate = self;
    [starTableView addSubview:s_refreshHeaderView];
    [s_refreshHeaderView refreshLastUpdatedDate];
}

#pragma mark - 검색중 나타나는 배경
-(void)makeSearchBGView{
    searchBGView = [[UIButton alloc] initWithFrame:CGRectMake(0, 44, mySize.width, mySize.height-20-44)];
    searchBGView.backgroundColor = ColorFromRGB(0x413c43);
    searchBGView.alpha = 0.85;
    [searchBGView addTarget:self action:@selector(searchBGViewButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:searchBGView];
    searchBGView.hidden = YES;
}

-(void)searchBGViewButtonAction:(id)sender{
    [mSearchView resignFirstResponder];
    [self hiddenAutoSearchView];
}

-(void)apearSearchBGView:(BOOL)yn{
    
    searchBGView.hidden = NO;
    searchBGView.alpha = yn ? 0.0f : 0.85f;
    
    [UIView animateWithDuration:0.4f animations:^{
        searchBGView.alpha = yn ? 0.85 : 0.0f;
    } completion:^(BOOL finished) {
        searchBGView.hidden = !yn;
    }];
    
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
/*
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    [super drawRect:rect];
}*/



#pragma mark - 위로가기
-(void)topMoveButtonAction:(id)sender{
    if (!issueTableView.hidden) {
        [issueTableView setContentOffset:CGPointMake(0, 0) animated:YES];
    }else if(!starTableView.hidden){
        [starTableView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}

#pragma mark - 뒤로
-(void)backButtonAction:(id)sender{
    
    [appDelegate removeActivity];
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController removeSearchView];
}

#pragma mark - 이슈&스타 선택

//선택
-(void)starButtonAction:(id)sender{
    
    starButton.selected = YES;
    issueButton.selected = NO;
    [self selectIssueView:NO];
    if (requestStar) {
        [self searchKeyword:self.currentKeyword andIssue:NO andPageNumber:1];
        requestStar = NO;
    }
}

-(void)issueButtonAction:(id)sender{
    issueButton.selected = YES;
    starButton.selected = NO;
    [self selectIssueView:YES];
    if (requestIssue) {
        [self searchKeyword:self.currentKeyword andIssue:YES andPageNumber:1];
        requestIssue = NO;
    }
}

-(void)selectIssueView:(BOOL)yn{
    
    if (duringNetwork) {
        return;
    }
    if (yn) {
        issueTableView.hidden = NO;
        starTableView.hidden = YES;
        resultCountLabel.text = issueTotalCount(self.issueCount);
        requestIndex = 2;
        
    }else{
        issueTableView.hidden = YES;
        starTableView.hidden = NO;
        resultCountLabel.text = starTotalCount(self.starCount);
        requestIndex = 1;
    }
}

#pragma mark - 스타 액션
-(void)listLeftButtonClick:(id)sender{
    
    UIButton *button = (UIButton*)sender;
    [self appearStarListToID:button.tag];
}

-(void)rightLeftButtonClick:(id)sender{
    
    UIButton *button = (UIButton*)sender;
    [self appearStarListToID:button.tag];
}

-(void)appearStarListToID:(NSInteger)index{
    
    ViewController *viewController = (ViewController*)self.window.rootViewController;
    NSString *starID = [[self.starArray objectAtIndex:index] objectForKey:@"content_id"];
    
    [viewController appearStarListToID:starID];
}

#pragma mark - 자동완성
-(void)apearAutoSearchList:(NSArray*)list andText:(NSString*)text{
    
    if (!autoSearchView) {
        autoSearchView = [[AutoSearchView alloc] initWithFrame:CGRectMake(mSearchView.frame.origin.x, mSearchView.frame.origin.y+mSearchView.frame.size.height, mSearchView.frame.size.width, 0)];
        autoSearchView.backgroundColor = [UIColor whiteColor];
        [self addSubview:autoSearchView];
    }
    
    float height = (list.count > 6) ? 25*6 : list.count*25;
    autoSearchView.delegate = self;
    autoSearchView.frame = CGRectMake(mSearchView.frame.origin.x, mSearchView.frame.origin.y+mSearchView.frame.size.height-10, mSearchView.frame.size.width, height+10);
    [autoSearchView.mList removeAllObjects];
    [autoSearchView.mList addObjectsFromArray:list];
    autoSearchView.mWord = text;
    autoSearchView.layer.cornerRadius = 10.0f;
    [autoSearchView setTableWithThisRect:autoSearchView.frame];
    autoSearchView.backgroundColor = [UIColor whiteColor];
    autoSearchView.hidden = NO;
}

-(void)hiddenAutoSearchView{
    if (autoSearchView) {
        
        autoSearchView.hidden = YES;
    }
}

//자동검색창에서 넘어옴
-(void)autoKeyword:(NSString*)keyword{
    
    [self hiddenAutoSearchView];
    [mSearchView resignFirstResponder];
    
    [self searchKeyword:keyword andIssue:issueButton.selected andPageNumber:1];
    
    mSearchView.text = keyword;
    self.currentKeyword = keyword;
    requestIssue = !issueButton.selected;
    requestStar = !starButton.selected;
}

//검색어 포함된 array
- (NSArray*)findArrayFromWord:(NSString*)word
{
    
    NSMutableArray *words = (NSMutableArray*)appDelegate.autoSearchArray;
    
    NSString *temp = [NSString stringWithFormat:@"*%@*",word];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF LIKE %@", temp];
    NSMutableArray *fetchedArray = (NSMutableArray*)[words filteredArrayUsingPredicate:predicate];
    return [self lineupArray:fetchedArray andWord:word];
}

//정렬
-(NSArray*)lineupArray:(NSMutableArray*)targetArray andWord:(NSString*)word{
    
    for (int i = 0; i<[targetArray count]; i++) {
        
        NSMutableArray *orderAr = [NSMutableArray array];
        for (int i=0; i<[targetArray count]; i++)
        {
            NSString *resultstring = [targetArray objectAtIndex:i];
            NSRange range = [resultstring rangeOfString:word];
            NSString *newstring = [NSString stringWithFormat:@"%d_%d",range.location,i];
            
            [orderAr addObject:newstring];
            
        }
        
        NSArray *sortedArray = [orderAr sortedArrayUsingComparator:^(id firstObject, id secondObject) {
            return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
        }];
        
        
        
        NSMutableArray *newAr = [NSMutableArray array];
        
        for (int i=0; i<[sortedArray count]; i++) {
            
            NSArray *parseAr = [[sortedArray objectAtIndex:i] componentsSeparatedByString:@"_"];
            
            int index = [[parseAr lastObject] intValue];
            NSString *insertstring = [targetArray objectAtIndex:index];
            [newAr addObject:insertstring];
            
            
            
        }
        
        //  [words removeAllObjects];
        targetArray = [NSMutableArray arrayWithArray:newAr];
    }
    return (NSArray*)targetArray;
}
#pragma mark - UIactivityLoading

-(void)makeActivityIndicatorView{
    activieiBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mySize.width, 50)];
    activieiBGView.backgroundColor = ColorFromRGB(0x413c43);

    
    activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityView.center = CGPointMake(activieiBGView.frame.size.width*0.5f, 25);
    [activieiBGView addSubview:activityView];

}

-(void)makeActivityIndicatorView2{
    activieiBGView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mySize.width, 50)];
    activieiBGView2.backgroundColor = ColorFromRGB(0x413c43);
    
    
    activityView2 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityView2.center = CGPointMake(activieiBGView2.frame.size.width*0.5f, 25);
    [activieiBGView2 addSubview:activityView2];
    
}

#pragma mark - 페이지

-(void)loadNextPage{
    
    if (issueButton.selected) {
        //이슈
        [self searchKeyword:self.currentKeyword andIssue:YES andPageNumber:self.currentIssuePageNumber];
    }else{
        //스타
        [self searchKeyword:self.currentKeyword andIssue:NO andPageNumber:self.currentStarPageNumber];
    }
}


#pragma mark - 스크롤잡기

- (void)reloadTableViewDataSource{
	
    _reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
    
    
    _reloading = NO;
    [i_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:issueTableView];
    [s_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:starTableView];
	
}

#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
    return _reloading;
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}


#pragma mark - 네트워크
-(void)searchKeyword:(NSString *)keyword andIssue:(BOOL)yn andPageNumber:(NSInteger)pagenum{
    
    if ([keyword length] <= 0) {
        return;
    }
    
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_SEARCH Label:ANA_LAB_Search_Result];
    
    NSString *url = nil;
    pagenum = (pagenum < 1) ? 1:pagenum;
    requestIndex = yn ? 2:1;
    self.currentKeyword = keyword;
    
    if (yn) {
        [activityView startAnimating];
        if (pagenum == 1) {
            
            [issueArray removeAllObjects];
            self.currentIssuePageNumber = 1;    //이슈뷰 현재페이지 넘버
        }
    }else{
        [activityView2 startAnimating];
        if (pagenum == 1) {
            
            [starArray removeAllObjects];
            self.currentStarPageNumber = 1;
        }
    }
    
    NSLog(@"키워드 : %@ | %@ | 페이지 : %d",keyword,yn?@"이슈":@"스타",pagenum);
    
    NSString *dataStr = [NSString stringWithFormat:@"keyword=%@&type=%d&page=%ld&lang=%@&pagesize=100",keyword,yn?2:1,(long)pagenum,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    url = [NSString stringWithFormat:@"%@?p=%@",URL_SEARCH,dataStr];
    [self startRequestWithURL:url];
}

-(void)requestURL:(NSString*)url{

//    [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5, mySize.height*0.5-30)];
    [self performSelectorOnMainThread:@selector(startRequestWithURL:) withObject:url waitUntilDone:NO];
}

-(void)startRequestWithURL:(NSString*)url{
    @autoreleasepool {
        
        duringNetwork = YES;
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
            [request setHTTPMethod:@"POST"];
            
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            if(connection){
                NSLog(@"이슈리스트 네트워크 요청 : %@",url);
            }else{
                
            }
            
        }
    }
}


#pragma mark delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    duringNetwork = NO;
    
    NSError *myError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    
//    NSLog(@"검색결과 리스트 : %@",resultDictionary);
    NSString *imageURL = [resultDictionary objectForKey:@"imgurl"];
    NSLog(@"search result dic : %@",resultDictionary);
    
    if ([resultDictionary objectForKey:@"return_code"]) {
        if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
            
            resultDictionary = [resultDictionary objectForKey:@"data"];
            if (requestIndex == 2) {
                //이슈
                
                NSArray *items = ([appDelegate checkObject:[resultDictionary objectForKey:@"items"]]) ? [resultDictionary objectForKey:@"items"] : nil;
                if (items) {
                    [self.issueArray addObjectsFromArray:items];
                }
                
                self.issueIsEnd = ([appDelegate checkObject:[resultDictionary objectForKey:@"isend"]]) ? [[resultDictionary objectForKey:@"isend"] boolValue] : NO;
                self.issueCount = ([appDelegate checkObject:[resultDictionary objectForKey:@"total"]]) ? [[resultDictionary objectForKey:@"total"] integerValue] : 0;
                self.issueImageURL = imageURL;
                
                //검색결과
                if (!issueTableView.hidden) {
                    resultCountLabel.text = issueTotalCount(self.issueCount);
                }
                
                if (!issueTableView) {
                    [self makeIssueView];
                }
                [issueTableView reloadData];
                
                NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
                [notification postNotificationName:ITEM_LIST_LOAD object:self.issueArray];
                [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.5f];
                
            }else if(requestIndex == 1){
                //스타
                NSArray *items = ([appDelegate checkObject:[resultDictionary objectForKey:@"items"]]) ? [resultDictionary objectForKey:@"items"] : nil;
                if (items) {
                    [self.starArray addObjectsFromArray:items];
                }
                
                self.starIsEnd = ([appDelegate checkObject:[resultDictionary objectForKey:@"isend"]]) ? [[resultDictionary objectForKey:@"isend"] boolValue] : NO;
                self.starCount = ([appDelegate checkObject:[resultDictionary objectForKey:@"total"]]) ? [[resultDictionary objectForKey:@"total"] integerValue] : 0;
                self.starImageURL = imageURL;

                //검색결과
                if (!starTableView.hidden) {
                    resultCountLabel.text = starTotalCount(self.starCount);
                }
                
                if (!starTableView) {
                    [self makeStarView];
                }
                [starTableView reloadData];
                
                NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
                [notification postNotificationName:ITEM_LIST_LOAD object:self.starArray];
                [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.5f];
                
            }
        }
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    duringNetwork = NO;
    NSLog(@"검색_이슈리스트 네트워크 요청 실패 : %@",error);
}

#pragma mark - UITableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        
        if (tableView.tag == 1) {
            //이슈
            return [self.issueArray count];
        }else{
            NSInteger numberOfRows = ([self.starArray count]%2 == 0) ? (int)([self.starArray count]/2) : (int)([self.starArray count]/2)+1;
            return numberOfRows;
        }
    }else{
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        if (tableView.tag == 1) {
            //이슈
            return 90;
        }else if(tableView.tag == 2){
            //스타
            return 147;
        }else{
            return 44;
        }
    }else{
        return 44;
    }

}

/*
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (tableView.tag == 1) {
        return (issueCount > 0) ? [NSString stringWithFormat:@"%d%@",issueCount, NSLocalizedString(@"searchissue", @"searchissue")] : NSLocalizedString(@"nosearch", @"nosearch");
    }else{
        return (starCount > 0) ? [NSString stringWithFormat:@"%d%@",starCount, NSLocalizedString(@"searchresult", @"searchresult")] : NSLocalizedString(@"nosearch", @"nosearch");
    }
}*/

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    if (tableView.tag == 1) {
        
        if (indexPath.section == 0) {
            
            //이슈
            static NSString *cellIDSearchIssue = @"cellIDSearchIssue";
            SecondTypeListCell *cell = (SecondTypeListCell*)[tableView dequeueReusableCellWithIdentifier:cellIDSearchIssue];
            if (cell == nil) {
                cell = [[SecondTypeListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIDSearchIssue];
            }
            
            
            if (duringNetwork) {
                return cell;
            }
            
            //재사용시 기존 이미지 가림
            if (!cell.photoImage.image || cell.photoImage.tag != indexPath.row) {
                cell.photoImage.image = nil;
            }
            
            NSString *mediaType = [[self.issueArray objectAtIndex:indexPath.row] objectForKey:@"media_type"];
            mediaType = [appDelegate setMediaType:mediaType];
            NSString *date = [[self.issueArray objectAtIndex:indexPath.row] objectForKey:@"date"];
            
            cell.dateTitle.text = [NSString stringWithFormat:@"%@ %@",mediaType,date];
            cell.mainTitle.text = [[self.issueArray objectAtIndex:indexPath.row] objectForKey:@"title"];
            cell.subTitle.text = [[self.issueArray objectAtIndex:indexPath.row] objectForKey:@"sub_title"];
            cell.photoImage.tag = indexPath.row;
            
            NSString *url = [[self.issueArray objectAtIndex:indexPath.row] objectForKey:@"thumb_url"];
            //        url = [NSString stringWithFormat:@"%@%@",self.issueImageURL,url];
            
            [appDelegate loadAsyncImageFromDomain:self.issueImageURL andFileName:url imageBlock:^(UIImage *image) {
                
                if (cell.photoImage.tag == indexPath.row) {
                    cell.photoImage.image = image;
                    
                    [appDelegate effectFaceoutTargetView:cell.photoImage];
                }
                
            } errorBlock:^{
                
                NSLog(@"검색>이슈 이미지호출 실패");
            }];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor clearColor];
            return cell;
        }else{
            
            static NSString *CellIdentifier = @"UITableViewCell_Search_issue";
            UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                [self makeActivityIndicatorView];
                [cell.contentView addSubview:activieiBGView];
            }
            
            if (issueArray.count > 0 && self.issueIsEnd) {
                
                [activityView startAnimating];
            }
            
            return cell;
            
        }
        
    }else if(tableView.tag == 2){
        
        
        //스타
        
        if (indexPath.section == 0) {
            static NSString *cellIDSearchStar = @"cellIDSearchStar";
            ListCell *cell = (ListCell*)[tableView dequeueReusableCellWithIdentifier:cellIDSearchStar];
            if (cell == nil) {
                cell = [[ListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIDSearchStar];
                cell.delegate = self;
            }
            
            if (duringNetwork) {
                return cell;
            }
            
            NSString *first, *second;
            NSString *firstURL, *secondURL;
            
            cell.leftButton.hidden = cell.rightButton.hidden = YES;
            
            if ((indexPath.row*2) < [self.starArray count]) {
                
                cell.leftButton.hidden = NO;
                
                //재사용시 기존 이미지 가림
                if (!cell.leftImage.image || cell.leftImage.tag != indexPath.row) {
                    cell.leftImage.image = nil;
                    [cell cellLeftIconImage:nil];
                }
                
                first = [[self.starArray objectAtIndex:indexPath.row*2] objectForKey:@"title"];
                firstURL = [NSString stringWithFormat:@"%@%@",self.starImageURL,[[self.starArray objectAtIndex:indexPath.row*2] objectForKey:@"thumb_url"]];
                cell.leftImage.tag = indexPath.row;
                cell.leftButton.tag = indexPath.row*2;
                [cell.leftButton addTarget:self action:@selector(listLeftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                
                [appDelegate loadAsyncImageFromDomain:self.starImageURL andFileName:[[self.starArray objectAtIndex:indexPath.row*2] objectForKey:@"thumb_url"] imageBlock:^(UIImage *image) {
                    if (cell.leftImage.tag == indexPath.row) {
                        
                        cell.leftImage.image = image;
                        [appDelegate effectFaceoutTargetView:cell.leftImage];
                    }
                } errorBlock:^{
                    if (cell.leftImage.tag == indexPath.row) {
                        
                        cell.leftImage.image = nil;
                    }
                }];
                
                //리본아이콘
                NSString *icon = [[self.starArray objectAtIndex:indexPath.row*2] objectForKey:@"icon"];
                if ([appDelegate checkObject:icon]) {
                    NSString *imgurl = [appDelegate.iconDictionary objectForKey:icon];
                    cell.leftIcon.tag = indexPath.row;
                    
                    [appDelegate loadAsyncImageFromURLString:imgurl imageBlock:^(UIImage *image) {
                        if (cell.leftIcon.tag == indexPath.row) {
                            
                            [cell cellLeftIconImage:image];
                        }
                    } errorBlock:^{
                        
                        [cell cellLeftIconImage:nil];
                    }];
                }
                
            }
            if ((indexPath.row*2)+1 < [self.starArray count]) {
                
                cell.rightButton.hidden = NO;
                
                //재사용시 기존 이미지 가림
                if (!cell.rightImage.image || cell.rightImage.tag != indexPath.row) {
                    cell.rightImage.image = nil;
                }
                
                second = [[self.starArray objectAtIndex:(indexPath.row*2)+1] objectForKey:@"title"];
                secondURL = [NSString stringWithFormat:@"%@%@",self.starImageURL,[[self.starArray objectAtIndex:(indexPath.row*2)+1]objectForKey:@"thumb_url"]];
                cell.rightImage.tag = indexPath.row;
                cell.rightButton.tag = (indexPath.row*2)+1;
                [cell.rightButton addTarget:self action:@selector(rightLeftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                
                
                [appDelegate loadAsyncImageFromDomain:self.starImageURL andFileName:[[self.starArray objectAtIndex:(indexPath.row*2)+1]objectForKey:@"thumb_url"] imageBlock:^(UIImage *image) {
                    
                    if (cell.rightImage.tag == indexPath.row) {
                        
                        cell.rightImage.image = image;
                        [appDelegate effectFaceoutTargetView:cell.rightImage];
                    }
                } errorBlock:^{
                    if (cell.rightImage.tag == indexPath.row) {
                        
                        cell.rightImage.image = nil;
                    }
                }];
                
                //리본아이콘
                NSString *icon = [[self.starArray objectAtIndex:(indexPath.row*2)+1] objectForKey:@"icon"];
                
                if ([appDelegate checkObject:icon]) {
                    NSString *imgurl = [appDelegate.iconDictionary objectForKey:icon];
                    cell.rightIcon.tag = indexPath.row;
                    
                    
                    [appDelegate loadAsyncImageFromURLString:imgurl imageBlock:^(UIImage *image) {
                        if (cell.leftIcon.tag == indexPath.row) {
                            
                            [cell cellRightIconImage:image];
                        }
                    } errorBlock:^{
                        
                        [cell cellRightIconImage:nil];
                    }];
                    
                }
            }
            
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell cellOfIssueWithHotList:nil andFirstTitle:first andSecondTitle:second];
            cell.leftTitle.textAlignment = cell.rightTitle.textAlignment = NSTextAlignmentCenter;
            
            return cell;
            
        }else{
            
            static NSString *CellIdentifier = @"UITableViewCell_Search_Star";
            UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                [self makeActivityIndicatorView2];
                [cell.contentView addSubview:activieiBGView2];
            }
            if (starArray.count > 0 && self.starIsEnd) {
                
                [activityView2 startAnimating];
            }
            
            return cell;
        }
        
    }else{
        return nil;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 1) {
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        
        NSString *issueID = [[self.issueArray objectAtIndex:indexPath.row] objectForKey:@"content_id"];
        NSLog(@"issueID : %@",issueID);
        PhotoViewController *photoController = [[PhotoViewController alloc] init];
        photoController.parentClassIndex = 5;
        photoController.adCount = appDelegate.issueAdCount;
        photoController.mDelegate = self;
        photoController.issuesList = self.issueArray;
        [photoController setIssueIndex:indexPath.row];
        [photoController requestIssueID:issueID];
        [viewController presentModalViewController:photoController animated:YES];
    }
}

#pragma mark - UIScrollView Delegate
//다음페이지 이동
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (!duringNetwork) {
        
        if (requestIndex == 1) {
            //스타
            
            if (([scrollView contentOffset].y+scrollView.frame.size.height) == [scrollView contentSize].height && self.starIsEnd) {
                
                NSLog(@"scrollViewDidEndDecelerating");
                self.currentStarPageNumber++;
                [self searchKeyword:self.currentKeyword andIssue:NO andPageNumber:self.currentStarPageNumber];
            }
            
        }else if(requestIndex == 2){
            //이슈
            if (([scrollView contentOffset].y+scrollView.frame.size.height) == [scrollView contentSize].height && self.issueIsEnd) {
                
                NSLog(@"scrollViewDidEndDecelerating");
                self.currentIssuePageNumber++;
                [self searchKeyword:self.currentKeyword andIssue:YES andPageNumber:self.currentIssuePageNumber];
            }
        }
        
        
    }
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController sdkHidden:NO];
    topMoveButton.hidden = NO;
}

//업데이트
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (issueButton.selected) {
        if (issueArray.count > 0) {
            
            [i_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
        }
        
    }else{
        if (starArray.count > 0) {
            
            [s_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
        }
    }
    
    if (!duringNetwork) {
        if (scrollView.contentOffset.y < -50) {
            [self searchKeyword:self.currentKeyword andIssue:(requestIndex == 2) andPageNumber:1];
        }
    }
    
    if (!decelerate) {
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        [viewController sdkHidden:NO];
        topMoveButton.hidden = NO;
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController sdkHidden:YES];
    topMoveButton.hidden = YES;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    if (issueButton.selected) {
        
        [i_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }else{
        [s_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
    
    
}


#pragma mark - UISearchBar Delegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //처음에 서치바 진입시
    [self apearSearchBGView:YES];
    return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    [self apearSearchBGView:NO];
    return YES;
}
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    return YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    //키보드 입력2
    
    if ([searchText length] > 0) {
        
        [autoArray removeLastObject];
        [autoArray setArray:[self findArrayFromWord:searchText]];
        if ([autoArray count] > 0) {
            
            [self apearAutoSearchList:autoArray andText:searchText];
        }
    }else{
        [self hiddenAutoSearchView];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    //검색버튼 클릭
    
    [self hiddenAutoSearchView];
    [searchBar resignFirstResponder];
    
    
    if ([searchBar.text length] > 0) {
        
        [self searchKeyword:searchBar.text andIssue:issueButton.selected andPageNumber:1];
        
        self.currentKeyword = searchBar.text;
        requestIssue = !issueButton.selected;
        requestStar = !starButton.selected;
    }
}



@end
